#include "fun.h"

u8 bdata com;
sbit BUZZER = com^6;
sbit RELAY = com^4;

u8 key_value = 0;
extern u8 last_time_param;
extern u8 last_tem_param;
extern u8 last_led_param;
extern u8 time_param;
extern u8 tem_param;
extern u8 led_param;
extern bit disp_status;
extern u8 data_flag;
extern u8 param_flag;

void buzzer(u8 cmd)
{
	BUZZER = cmd;
	P0 = com;
	P2 = 0xa0;
	_nop_();
	P2 = 0x00;
}

void relay(u8 cmd)
{
	RELAY = cmd;
	P0 = com;
	P2 = 0xa0;
	_nop_();
	P2 = 0x00;
}

void led(u8 ucode)
{
	P0 = ~ucode;
	P2 = 0x80;
	_nop_();
	P2 = 0x00;
}

void smg_disp(u8 num,u8 position)
{
	P0 = 0xff;
	P2 = 0xe0;
	_nop_();
	P2 = 0x00;

	P0 = position;
	P2 = 0xc0;
	_nop_();
	P2 = 0x00;

	P0 = ~num;
	P2 = 0xe0;
	_nop_();
	P2 = 0x00;
}

void key_scan(void)
{
	static u8 key_up = 1;
	u16 key_value = 0;
	
	P44 = 0; P42 = 1;
	P35 = 1; P34 = 1;

	key_value = P3 & 0x0f; 

	P42 = 0; P44 = 1;
	key_value = (key_value << 4) | (P3 & 0x0f); 

	P35 = 0; P42 = 1;
	key_value = (key_value << 4) | (P3 & 0x0f); 

	P34 = 0; P35 = 1;
	key_value = (key_value << 4) | (P3 & 0x0f); 
	P34 = 1;
	
	key_value = ~key_value;
	
	if(key_up && key_value)
	{
		key_up = 0;
		if(key_value == 0x8000)
		{
			disp_status = ~disp_status;
			if(!disp_status)
			{
				data_flag = 0;
				last_time_param = time_param;
				last_tem_param = tem_param;
				last_led_param = led_param;
			}
			else
				param_flag = 0;
		}
		
		else if((key_value == 0x4000) && (!disp_status))
		{
			if(++data_flag == 3)		//时间，温度，亮暗状态
					data_flag = 0;
		}	
		else if((key_value == 0x4000) && (disp_status))
		{
			if(++param_flag == 3)		//时间，温度，亮暗状态
				
					param_flag = 0;
		}
		else if(key_value == 0x0800 && disp_status)
		{
			if(!param_flag && time_param < 23)
				time_param += 1;
			else if(param_flag == 1 && tem_param < 99)
				tem_param += 1;
			else if(param_flag == 2 && led_param < 8)
				led_param += 1;
		}
		else if(key_value == 0x0400 && disp_status)
		{
			if(!param_flag && time_param > 0)
				time_param -= 1;
			else if(param_flag == 1 && tem_param > 0)
				tem_param -= 1;
			else if(param_flag == 2 && led_param > 4)
				led_param -= 1;
		}
	}
	else if(key_value == 0)
		key_up = 1;
}
